02. Big Picture & Intuition

Big Picture and Developing Your Intuition about Functional Programming

ND079 JPND C2 L01 A02 Big Picture And Intuition V3

Imperative Code

Early Java programs were usually programmed in the imperative style. Imperative code usually focuses on how a task is performed. Each line of code gives a specific procedure or operation:

int getTopScore(List<Student> students) {
 int topScore = 0;
 for (Student s : students) {
   if (s == null) continue;
   topScore = Math.max(topScore, s.getScore());
 }
 return topScore;
}
  • Focuses on how a task is performed.
  • Each line of code gives a specific procedure or operation.

Imperative programs

Which of these are elements of imperative programs?

SOLUTION:
  • `for` loops and `while` loops
  • Individual steps about _how_ a task is performed

Functional Code

Starting with version 8, Java added language features to support a more functional style of programming. You might also hear some people call it declarative programming.

Functional code focuses on what happens to inputs in order to produce outputs. You can think of it as describing how to get from the input to the output:

int getTopScore(List<Student> students) {
 return students.stream()
     .filter(Objects::nonNull)
     .mapToInt(Student::getScore)
     .max()
     .orElse(0);
}

This code does the exact same thing as the last code example, but it uses a more functional programming style, because it:

  • Focuses on what happens to inputs in order to produce outputs..
  • Describes how to transform the input into the output.

Which of these are elements of functional programming in Java?

SOLUTION:
  • Lambda expressions
  • Streams
  • step-by-step transformation of _what_ is happening to inputs

Functional vs Imperative Code

  • There is nothing wrong with either imperative or functional styles of programming.
  • Anything you can do with one, you can do with the other.
  • Whether to use one or the other often boils down to your specific scenario, and your personal preference as a programmer.